package com.taoyuanx.boot.common;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.taoyuanx.boot.anno.NotNeedToken;
import com.taoyuanx.boot.business.TokenBusiness;
import com.taoyuanx.boot.eum.TokenResult;

@Component
public class HeaderIncepter  implements HandlerInterceptor {
	public static final String TOKEN_KEY="token";
	public static final Logger log=LoggerFactory.getLogger(HeaderIncepter.class);
	@Autowired
	TokenBusiness tokenBusiness;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod=(HandlerMethod) handler;
		NotNeedToken methodTokenAnno = handlerMethod.getMethod().getAnnotation(NotNeedToken.class);
		if(null!=methodTokenAnno){
			return methodTokenAnno.notNeed();
		}
		NotNeedToken classTokenAnno = handlerMethod.getBeanType().getAnnotation(NotNeedToken.class);
		if(null!=classTokenAnno){
			return classTokenAnno.notNeed();
		}
		String token = request.getHeader(TOKEN_KEY);
		Object tokenResult = tokenBusiness.vafyToken(token);
		if(tokenResult instanceof TokenResult ){
			TokenResult temp=(TokenResult) tokenResult;
			responseResult(response, ResultBuilder.failBuilder().
					buildCode(temp.code).buildMsg(temp.msg).build());
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	private void responseResult(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
        	log.error("异常信息为{}",ex);
        }
    }

	
}
